package org.moonlight.push.server.ios;

import com.turo.pushy.apns.ApnsClient;
import com.turo.pushy.apns.ApnsClientBuilder;
import com.turo.pushy.apns.DeliveryPriority;
import com.turo.pushy.apns.PushNotificationResponse;
import com.turo.pushy.apns.util.ApnsPayloadBuilder;
import com.turo.pushy.apns.util.SimpleApnsPushNotification;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.moonlight.push.server.BaseMessage;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 参考: https://github.com/jchambers/pushy
 *
 * @author Moonlight
 */
@Slf4j
public class IosClient {
    private final static String P12_PASS = "";
    private final static String APNS_SERVER = "";
    private final static String APNS_PORT = "";
    private final static String APP_PKG = "";
    private final static String P12_FILE = "";

    private final static IosClient INSTANCE = new IosClient();

    private boolean init = false;
    private ApnsClient apnsClient = null;

    private IosClient() {
        if (!init()) {
            throw new RuntimeException("IosClient初始化失败");
        }
    }

    private boolean init() {
        if (init) {
            return true;
        }
        if (StringUtils.isAnyBlank(P12_PASS, APNS_SERVER, APNS_PORT, APP_PKG, P12_FILE)) {
            log.error("[IosClient init] IosClient初始化失败. 关键配置项不应该为空. ");
            return false;
        }
        try {
            InputStream instream = null;
            try {
                instream = new FileInputStream(P12_FILE);
            } catch (Exception e) {
                log.error("[IosClient init] 读取p12File[{}]文件时出错. ", P12_FILE, e);
                return false;
            }

            apnsClient = new ApnsClientBuilder()
                    .setClientCredentials(instream, P12_PASS)
                    .setApnsServer(APNS_SERVER, Integer.parseInt(APNS_PORT))
                    .build();
        } catch (Exception e) {
            log.error("[IosClient init] 创建ApnsClient对象时出错. ", e);
            return false;
        }
        this.init = true;
        return true;
    }

    public boolean pushMessage(BaseMessage msg) {
        ApnsPayloadBuilder builder = new ApnsPayloadBuilder()
                .setAlertTitle(msg.getAlertTitle())
                .setAlertBody(msg.getAlertContent())
                .setContentAvailable(true);

        String iosMsg = builder.buildWithDefaultMaximumLength();

        SimpleApnsPushNotification notification = new SimpleApnsPushNotification(
                msg.getReceiverId(), APP_PKG, iosMsg, null, DeliveryPriority.IMMEDIATE, msg.getMsgId()
        );
        Future<PushNotificationResponse<SimpleApnsPushNotification>> future = apnsClient.sendNotification(notification);

        try {
            PushNotificationResponse<SimpleApnsPushNotification> resp = future.get(10, TimeUnit.SECONDS);

            log.info("[IosClient pushMessage] msg[{}] iosMsg[{}] resp.isAccepted[{}] resp.getRejectionReason[{}]",
                    msg, iosMsg, resp.isAccepted(), resp.getRejectionReason());

            return resp.isAccepted();
        } catch (Exception e) {
            log.error("[IosClient pushMessage] msg[{}] iosMsg[{}]. ", msg, iosMsg, e);
        }
        return false;
    }

}
